import { Component,OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import {Headers,RequestOptions,URLSearchParams} from "@angular/http";
import { Location } from '@angular/common';
import {Info} from "./info";
import {Unit} from "./pmodule/unit";
import {Uinfo} from "./pmodule/uinfo";
import {UnitService} from "./pservice/unit.service";
import {PagerService} from "../../pagination/pager.service";
import {UtilService} from "./util.service";
import {HttpURLService} from "../../httpURL.service";
import {DatePipe} from "@angular/common";
declare var $: any;
declare var jQuery: any;
@Component({
  selector: 'app-unit',
  templateUrl: './unit.component.html',
  styleUrls: ['./unit.component.css']
})
export class UnitComponent implements OnInit {
  //清除
searchpolluterName:"";
  searchtradeType:"";
  searchareaCode="";
  searchlegalUser:"";
  searchuserCode:"";
  searchorgCode:"";
  //清除添加
  polluterName:'';
  polluterSname:'';
  orgCode:'';
  userCode:'';
  Nature:'';
  cTime:'';
  areaCode:'';
  tradeType:'';
  electricity:'';
  polluter:'';
  longitude:'';
  attitude:'';
  waters:'';
  legalUser:'';
  legalCode:'';
  contact:'';
  contactNumber:'';
  bankName:'';
  bankAccount:'';
  email:'';
  address:'';
  /*  结束  */
  lookInfo:Unit = new Uinfo("","","","","","","","","","","","","","","","","","","","","","","","","");//查看详情信息
  query:Unit;//查询传参
  addInfo:Unit;//添加传参
  name:any;
  pageInfo = {
    totalItems: 0,
    currentPage: 1,
    pageSize: 10
  };
  dataUnit:any;//返回列表信息
  pchecked:boolean = false;
  isRemove:boolean = true;//点击移除删除弹框
  errorMessage:string;//错误信息
  typeCate:any;
  deleteId:'';//删除id   集体企业、联营企业、股份合作制企业、私营企业、个体户、合伙企业、有限责任公司、股份有限公司
//企业性质
  polluterNature=[{"id":0,"name":"国有企业"},{"id":1,"name":"集体企业"},{"id":2,"name":"联营企业"},{"id":3,"name":"股份合作制企业"},
    {"id":4,"name":"私营企业"},{"id":5,"name":"个体户"},{"id":6,"name":"合伙企业"},{"id":7,"name":"有限责任公司"},{"id":8,"name":"股份有限公司"}
  ];
  //流域
  watershed=[{"id":0,"name":"长江流域"},{"id":1,"name":"黄河流域"},{"id":2,"name":"珠江流域"},{"id":3,"name":"海河流域"},
    {"id":4,"name":"淮河流域"},{"id":5,"name":"松辽流域"},{"id":6,"name":"太湖流域"}
  ];
  arealist:'';//行政区列表
  zNodes:'';//行业类别
  dateStr:string;//时间格式化
  constructor(private http: HttpClient,
              location:Location,
              private unitService: UnitService,
              private pagerService: PagerService,
              private utilService: UtilService,
              private datePipe: DatePipe) {
  }
//查看and编辑
  userMessage(polluter:any){
    let unitObj = {};
    Object.assign(unitObj, polluter);
    this.lookInfo = unitObj;
    $("#citySeledit").val(polluter.name);
    this.dateStr =this.datePipe.transform(this.lookInfo.cTime, 'yyyy-MM-dd HH:mm:ss');
  }

//查询
  doSearch(query) {
    this.query = query;
    this.query.tradeType=$("#treadcode").val();
    this.pageInfo.currentPage = 1;
    this.getPageData();
  }
  cateSearch(query,n){
    this.name=query;
    this.typeCate=n;
    this.getcateData();
  }
  getcateData() {
    let queryObj = {};
    Object.assign(queryObj, this.name);
    const queryStr = this.utilService.toFormData(queryObj);
    this.getCates(queryStr,this.typeCate);
  }
  getCates(queryStr,n) {

    this.unitService.getcateList(queryStr).subscribe(data => {
        this.zNodes=data;
        if(n==1){ $.fn.zTree.init($(".ztree"), this.setting,this.zNodes);
        }else if(n==2){
          $.fn.zTree.init($(".ztree"), this.settingAdd,this.zNodes);
        }else{
          $.fn.zTree.init($(".ztree"), this.settingEdit,this.zNodes);
        }

      },
      error => this.errorMessage = <any>error
    );
  }
  //清除
  doClear(){
     this.searchpolluterName='';
     this.searchtradeType='';
     this.searchareaCode='';
     this.searchlegalUser='';
     this.searchuserCode='';
     this.searchorgCode='';
    $("#treadcode").val('');
    $("#citySel").val('');
    $(".form-control").val('');
  }
  setPage(toPageNum) {
    this.pageInfo.currentPage = toPageNum;
    this.getPageData();
  }
  //污染源列表
  getPageData() {
    let queryObj = {};
    Object.assign(queryObj, this.query,{
      limit: this.pageInfo.pageSize,
      /*current: (this.pageInfo.currentPage - 1) * this.pageInfo.pageSize*/
      current: this.pageInfo.currentPage
    });
    const queryStr = this.utilService.toFormData(queryObj);
    this.getExhibits(queryStr);
  }
  getExhibits(queryStr) {
    this.unitService.getExhibits(queryStr).subscribe(data => {
        this.dataUnit = data.records;
        this.pageInfo.totalItems = data.total;
      },
      error => this.errorMessage = <any>error
    );
  }
  //删除
  delete(pollutId) {
    this.deleteId=pollutId;
  }
  deletePollut(id) {
    this.unitService.deletePollut(id)
      .subscribe(
        data => {
          if(data.resultCode==0){
            $("#delete").modal('show');
          this.getPageData();
          }else if(data.resultCode==1){
            this.errorMessage = "删除失败！";
            $("#error").modal('show');
          } });
  }
  //行政区列表
  areaList() {
    this.unitService.getArea()
      .subscribe(
        data => {
          this.arealist=data;
        });
  }
  //添加
  doAdd(addInfo:any,valid:boolean){
    if(valid){
    this.addInfo = addInfo;
    this.addInfo.polluterName=addInfo.polluterName;
    this.addInfo.polluterSname=addInfo.polluterSname;
    this.addInfo.polluterNature=addInfo.Nature;
    this.addInfo.areaCode=addInfo.areaCode;
    this.addInfo.orgCode=addInfo.orgCode;
    this.addInfo.legalUser=addInfo.legalUser;
    this.addInfo.legalCode=addInfo.legalCode;
    this.addInfo.userCode=addInfo.userCode;
    this.addInfo.focusLevel=addInfo.focusLevel;
    this.addInfo.tradeType=$("#treadcodeadd").val();
    this.addInfo.isElectricity=addInfo.isElectricity;
    this.addInfo.isPolluter=addInfo.isPolluter;
    this.addInfo.longitude=addInfo.longitude;
    this.addInfo.attitude=addInfo.attitude;
    this.addInfo.watershed=addInfo.waters;
    this.addInfo.address=addInfo.address;
    this.addInfo.cTime=$("#startEndTime").val();
    this.addInfo.email=addInfo.email;
    this.addInfo.contact=addInfo.contact;
    this.addInfo.contactNumber=addInfo.contactNumber;
    this.addInfo.bankName=addInfo.bankName;
    this.addInfo.bankAccount=addInfo.bankAccount;
    this.addInfo.contact=addInfo.contact;
    this.addInfo.contactNumber=addInfo.contactNumber;
    this.addInfo.bankName=addInfo.bankName;

    this.unitService.createPollut(addInfo) .subscribe(
      data => {
        this.polluterName='';
        this.polluterSname='';
        this.polluterSname='';
        this.orgCode='';
        this.userCode='';
        this.Nature='';
        this.cTime='';
        this.areaCode='';
        this.tradeType='';
        this.electricity='';
        this.polluter='';
        this.longitude='';
        this.attitude='';
        this.waters='';
        this.legalUser='';
        this.legalCode='';
        this.contact='';
        this.contactNumber='';
        this.bankName='';
        this.bankAccount='';
        this.email='';
        this.address='';

        if(data.resultCode=='0'){
          $("#addModal").modal('hide');
        $("#topscroll").scrollTop(0);
          $("#add").modal('show');
        this.getPageData();
        }else {
          this.errorMessage = "添加失败！";
          $("#error").modal('show');
        }
      });
    }
  }
  //编辑
  doEdit(editInfo:any,valid:boolean){
    if(valid) {
      this.addInfo = editInfo;
      this.addInfo.id = editInfo.editid;
      this.addInfo.polluterName = editInfo.editpolluterName;
      this.addInfo.polluterSname = editInfo.editpolluterSname;
      this.addInfo.polluterNature = editInfo.editpolluterNature;
      this.addInfo.areaCode = editInfo.editareaCode;
      this.addInfo.orgCode = editInfo.editorgCode;
      this.addInfo.legalUser = editInfo.editlegalUser;
      this.addInfo.legalCode = editInfo.editlegalCode;
      this.addInfo.userCode = editInfo.edituserCode;
      this.addInfo.focusLevel = editInfo.editfocusLevel;
      this.addInfo.tradeType = $("#treadcodeedit").val();
      this.addInfo.isElectricity = editInfo.editisElectricity;
      this.addInfo.isPolluter = editInfo.editisPolluter;
      this.addInfo.longitude = editInfo.editlongitude;
      this.addInfo.attitude = editInfo.editattitude;
      this.addInfo.watershed = editInfo.editwatersh;
      this.addInfo.address = editInfo.editaddress;
      this.addInfo.email = editInfo.editemail;
      this.addInfo.contact = editInfo.editcontact;
      this.addInfo.contactNumber = editInfo.editcontactNumber;
      this.addInfo.bankName = editInfo.editbankName;

      this.addInfo.bankAccount = editInfo.editbankAccount;
      this.addInfo.contact = editInfo.editcontact;
      this.addInfo.contactNumber = editInfo.editcontactNumber;
      this.addInfo.bankName = editInfo.editbankName;
      this.unitService.editExhibit(editInfo).subscribe(
        data => {
          if(data.resultCode==0) {
            $("#updateModal").modal('hide');
            $("#update").modal('show');
            this.getPageData();
          }else {
            this.errorMessage = "编辑失败！";
            $("#error").modal('show');
          }});
    }
  }
  //时间插件
  dateRangePicker(){
    let picker:any=$('.startEndTime');
    let dataRageOption:Object={
      singleDatePicker: true,
      "timePicker": true,
      "timePicker24Hour": true,
      "drops": "down",
      "opens": "left",
      "locale": {
        "format": "YYYY-MM-DD HH:mm:ss",
        "separator": " -- ",
        "applyLabel": "应用",
        "cancelLabel": "取消",
        "fromLabel": "From",
        "toLabel": "To",
        "customRangeLabel": "Custom",
        "daysOfWeek": [
          "日",
          "一",
          "二",
          "三",
          "四",
          "五",
          "六"
        ],
        "monthNames": [
          "一月",
          "二月",
          "三月",
          "四月",
          "五月",
          "六月",
          "7月",
          "八月",
          "九月",
          "十月",
          "十一月",
          "十二月"
        ],
        "firstDay": 1
      },
      "startDate": new Date(),
    };
    picker.daterangepicker(dataRageOption,function (start,end,label) {
      this.cTime=start.format('YYYY-MM-DD HH:mm:ss');
    });

  }
  ngOnInit(){
    //获取分页信息
    this.getPageData();
    //时间
    this.dateRangePicker();
    this.areaList();
    this.getcateData();
  }

  setting = {
    check: {
      enable: true,
      chkStyle: "radio",
      radioType: "all"
    },
    view: {
      dblClickExpand: false
    },
    data: {
      simpleData: {
        enable: true
      }
    },
    callback: {
      beforeClick: this.beforeClick,
      onCheck: this.onCheck
    }
  };
  settingAdd = {
    check: {
      enable: true,
      chkStyle: "radio",
      radioType: "all"
    },
    view: {
      dblClickExpand: false
    },
    data: {
      simpleData: {
        enable: true
      }
    },
    callback: {
      beforeClick: this.beforeClick,
      onCheck: this.onCheckAdd
    }
  };
  settingEdit = {
    check: {
      enable: true,
      chkStyle: "radio",
      radioType: "all"
    },
    view: {
      dblClickExpand: false
    },
    data: {
      simpleData: {
        enable: true
      }
    },
    callback: {
      beforeClick: this.beforeClick,
      onCheck: this.onCheckEdit
    }
  };

  tarObj:any;

  beforeClick(treeId, treeNode) {
    let zTree = $.fn.zTree.getZTreeObj("ztree");
    zTree.checkNode(treeNode, !treeNode.checked, null, true);
    return false;
  }


  onCheck(e, treeId, treeNode) {
    let zTree = $.fn.zTree.getZTreeObj("ztree"),
      nodes = zTree.getCheckedNodes(true),
      v = "",
      a = "";
    for (let i=0, l=nodes.length; i<l; i++) {
      v += nodes[i].name + ",";
      a += nodes[i].id + ",";
    }
    if(v.length > 0){v = v.substring(0, v.length-1);}
    if(a.length > 0) {a = a.substring(0, a.length-1);}
    let cityObj = $("#citySel");
    let valueObj =$("#treadcode");
    cityObj.val(v);
    valueObj.attr("value", a);
  }
  onCheckAdd(e, treeId, treeNode) {
    let zTree = $.fn.zTree.getZTreeObj("ztree"),
      nodes = zTree.getCheckedNodes(true),
      v = "",
      a = "";
    for (let i=0, l=nodes.length; i<l; i++) {
      v += nodes[i].name + ",";
      a += nodes[i].id + ",";
    }
    if(v.length > 0){v = v.substring(0, v.length-1);}
    if(a.length > 0) {a = a.substring(0, a.length-1);}
    let  cityObj=$("#citySeladd");
    let valueObj =$("#treadcodeadd");
    cityObj.attr("value", v);
    valueObj.attr("value", a);
  }
  onCheckEdit(e, treeId, treeNode) {
    let zTree = $.fn.zTree.getZTreeObj("ztree"),
      nodes = zTree.getCheckedNodes(true),
      v = "",
      a = "";
    for (let i=0, l=nodes.length; i<l; i++) {
      v += nodes[i].name + ",";
      a += nodes[i].id + ",";
    }
    if(v.length > 0){v = v.substring(0, v.length-1);}
    if(a.length > 0) {a = a.substring(0, a.length-1);}
    let  cityObj = $("#citySeledit");
    let valueObj =$("#treadcodeedit");
    cityObj.val(v);
    valueObj.attr("value", a);
  }

  showMenu(n,id) {
    this.tarObj = n;
    let cityObj = $("#"+id);
    let cityOffset = $("#"+id).offset();
    if(n==1){
      $.fn.zTree.init($(".ztree"), this.setting,this.zNodes);
    }
    else if(n==2){
      $.fn.zTree.init($(".ztree"), this.settingAdd,this.zNodes);
    }else{
      $.fn.zTree.init($(".ztree"), this.settingEdit,this.zNodes);
    }
    $("#menuContent"+n).slideDown("fast");

    //$("body").bind("mousedown", this.onBodyDown);
  }
  closeZtree(query){
    $(".categroy").val('');
    $(".menuContent").fadeOut("fast");
    this.getcateData();
  }


}
